package org.gitman.agentplatform.ui.utils;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class LoggingPanel extends JPanel{

	private JTextPane logConsole;
	private StyledDocument doc;
	private Style info,warn,error;
	private Map<Level, Style> level2style;
	private Color infoColor = Color.black, warnColor = new Color(220,108,0), errorColor = Color.red;
	
	public LoggingPanel() {
		setLayout(new BorderLayout());
		logConsole = new JTextPane();
		logConsole.setEditable(false);
		doc = logConsole.getStyledDocument();
		info = doc.addStyle("info", null);
		StyleConstants.setForeground(info, infoColor);
		warn = doc.addStyle("warn", null);
		StyleConstants.setForeground(warn, warnColor);
		error = doc.addStyle("error", null);
		StyleConstants.setForeground(error, errorColor);
		
		level2style = new HashMap<LoggingPanel.Level, Style>(3);
		level2style.put(Level.INFO, info);
		level2style.put(Level.WARN, warn);
		level2style.put(Level.ERROR, error);	
		
		JScrollPane logPane = new JScrollPane(logConsole);
		add(logPane, BorderLayout.CENTER);
		JPanel legendPanel = new JPanel(new GridLayout(4,1));
		add(legendPanel,BorderLayout.EAST);
		legendPanel.add(new JLabel(" legend:"));
		JLabel iL = new JLabel("    info");
		iL.setForeground(infoColor);
		legendPanel.add(iL);
		JLabel wL = new JLabel("    warning");
		wL.setForeground(warnColor);
		legendPanel.add(wL);
		JLabel eL = new JLabel("    error");
		eL.setForeground(errorColor);
		legendPanel.add(eL);
	}
	
	public void appendConsole(String message, Level level){
		try {
			doc.insertString(doc.getLength(), message + "\n", level2style.get(level));
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
		logConsole.setCaretPosition(doc.getLength());
	}
	
	public enum Level{
		INFO, WARN, ERROR;
	}
	
}
